<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>基本资料</span>
    </div>
    <!-- 表单 -->
    <el-form :model="user" :rules="formRules" ref="formRef">
      <el-form-item label="登录名称" label-width="80px" label-position="right">
        <el-input disabled v-model="user.username"></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" label-width="80px" label-position="right" prop="nickname">
        <el-input v-model="user.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" label-width="80px" label-position="right" prop="email">
        <el-input v-model="user.email"></el-input>
      </el-form-item>
      <el-form-item label="" label-width="80px" >
        <el-button type="primary" @click="doChange">提交修改</el-button>
        <el-button type="info" @click="doReset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  name: 'UserInfo',
  data () {
    return {
      // 将vuex数据拷贝到data中 
      user: {...this.$store.state.user},
      // 表单校验规则
      formRules: {
        nickname: [
          {required: true, message: '请输入用户昵称', trigger: 'blur'},
          {pattern: /^\S{1,10}$/,  message: '昵称必须是1-到10位的非空字符串', trigger: 'blur'},
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {type: 'email',  message: '请输入正确的邮箱地址', trigger: ['blur', 'change']},
        ]
      }
    }
  },
  // methods:事件处理函数
  methods: {
    doChange() {
      this.$refs.formRef.validate(async valid => {
        // 通过发送ajax请求
        if (valid) {
          const res = await this.$axios.put('/my/userinfo', this.user)
          console.log(res)
          this.$message.success(res.data.message)
          if (res.data.code === 0) {
            this.$store.dispatch('getUserInfo')
          }
        }
      })
    },
    doReset() {
      // 这个重置是恢复el-form组件的初始状态(文本恢复默认 清除红色提示)
      this.$refs.formRef.resetFields()
    }
  },
  // 计算属性
  computed: {
    // user() {
    //   return this.$store.state.user
    // }
  },
}
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>
